#coding:utf-8
from mako.lookup import TemplateLookup
from model import datavalid, WebSiteModel, GuestBookModel, BlogModel, CategoryModel, TagModel, CommentModel
from bottle import request, redirect, abort
from google.appengine.api import users
from pager import Pager
from config import get_webpage_strings
import datetime
import os

adminlookup = TemplateLookup(directories=['./admin'], input_encoding='utf-8', output_encoding='utf-8', encoding_errors='replace')

class Admin():

    cmdtype_list = [
        'guestbook', 'blog', 'comment', 'config', 'category', 'tag',
    ]
    model = {
        #确定模型
        'guestbook': GuestBookModel,
        'blog': BlogModel,
        'comment': CommentModel,
        'category': CategoryModel,
        'tag': TagModel,
    }
    showtype = {
        'guestbook': 'greetings',
        'blog': 'dairies',
        'comment': 'comments',
        'category': 'categories',
        'tag': 'tags',
    }
    left = {
            #左侧边栏，写的不是很清楚，待修改
            'setting': [{'title': u'站点设置', 
                         'subs': [{'title': u'全局设置',
                                    'url': '/admincp/config'} ]}],
            'guestbook': [{'title': u'留言管理', 
                           'subs': [ {'title': u'留言管理', 
                                      'url': '/admincp/guestbook'} ,]}],
            'blog': [{'title': u'文章管理', 
                      'subs': [ {'title': u'文章管理', 
                                 'url': '/admincp/blog'} ,
                                 {'title': u'文章撰写', 
                                  'url': '/admincp/blog/post'} ,]},
                                   {'title': u'分类管理', 
                                    'subs': [{'title': u'分类管理', 
                                              'url': '/admincp/category'}, ]},
                                              {'title': u'标签管理', 
                                               'subs': [{'title': u'标签管理', 
                                                         'url': '/admincp/tag'}]}],
            'comment': [{'title': u'评论管理', 
                         'subs': [{'title': u'评论管理',
                                    'url': '/admincp/comment'} ,]}],
            'category':[{'title': u'文章管理', 
                         'subs': [ {'title': u'文章管理',
                                     'url': '/admincp/blog'} ,
                                     {'title': u'文章撰写', 
                                      'url': '/admincp/blog/post'} ,]}, 
                                      {'title': u'分类管理',
                                        'subs': [{'title': u'分类管理',
                                                   'url': '/admincp/category'}, ]},
                                                   {'title': u'标签管理', 
                                                    'subs': [{'title': u'标签管理', 
                                                              'url': '/admincp/tag'}]}],
            'tag':[{'title': u'文章管理', 
                    'subs': [ {'title': u'文章管理', 
                               'url': '/admincp/blog'} ,
                               {'title': u'文章撰写', 
                                'url': '/admincp/blog/post'} ,]}, 
                                {'title': u'分类管理', 
                                 'subs': [{'title': u'分类管理', 
                                           'url': '/admincp/category'}, ]},
                                           {'title': u'标签管理', 
                                            'subs': [{'title': u'标签管理', 
                                                      'url': '/admincp/tag'}]}],
     }
    def __init__(self, cmdtype):
        self.themelist = os.listdir('./theme')
        self.webpage = get_webpage_strings(now=u'控制面板')
        if not cmdtype in self.cmdtype_list:
            abort(404)
        else:
            self.cmdtype = cmdtype
            user = users.get_current_user()
            if not user:
                redirect(users.create_login_url("/admincp/"+self.cmdtype))
            else:
                self.right = {
                    #右侧边栏
                    'numofdairy': BlogModel.all().count(),
                    'numofcomment': CommentModel.all().count(),
                    'numofentry': GuestBookModel.all().count(),
                    'version': self.webpage['version']
                }
                if users.is_current_user_admin():
                    self.username = user.nickname()
                else:
                    abort(405)
    
    def config(self):
        '''
        页面设置
        '''
        if self.webpage['orderofcomment']:
            self.webpage.update({'order': '', 'rev': 'checked="checked"'})
        else:
            self.webpage.update({'rev': '', 'order': 'checked="checked"'})
        
        admintemplate = adminlookup.get_template('admincp.tpl')
        a = { 'webpage': self.webpage , 'leftsides': self.left['setting'], 'rightside': self.right, 'username': self.username, 'themes': self.themelist}
        return admintemplate.render(**a)
    
    def accept_config(self):
        '''
        提交页面设置
        '''
        website = WebSiteModel().get_by_id(ids=self.webpage['id'])
        result = {
            'title': datavalid(data=request.forms.get('title'),datatype='author'),
            'subtitle': datavalid(data=request.forms.get('subtitle'),datatype='author'),
            'houroffset': datavalid(data=request.forms.get('houroffset'),datatype='num'),
            'numofentry': datavalid(data=request.forms.get('numofentry'),datatype='num'),
            'numofgreeting': datavalid(data=request.forms.get('numofgreeting'),datatype='num'),
            'numofcomment': datavalid(data=request.forms.get('numofcomment'),datatype='num'),
            'orderofcomment': datavalid(data=request.forms.get('orderofcomment'),datatype='num'),
            'owner': datavalid(data=request.forms.get('owner'),datatype='author'),
            'theme':request.forms.get('theme'),
        }
        #数据验证部分，如果有更好的写法再修改
        if all(result):
            website.orderofcomment = int(result['orderofcomment'])
            website.title = result['title']
            website.subtitle = result['subtitle']
            website.timeoffset = int(result['houroffset'])
            website.numofentry = int(result['numofentry'] )
            website.numofgreeting = int(result['numofgreeting'])
            website.numofcomment = int(result['numofcomment'])
            website.owner = result['owner']
            website.theme = result['theme']
            website.save()
            self.redirect('success')
        self.redirect('fail')
    
    def list(self, num):
        '''
        显示列表
        '''
        show_list = self.model[self.cmdtype].all().order('-__key__')
        page = Pager(query=show_list,page_length=20)
        if not show_list:
            return 'No Result'
        else:
            admintemplate = adminlookup.get_template(self.cmdtype+'.tpl')
            show_list2, links = page.fetch(curpage=num)
            a = { 'webpage': self.webpage, self.showtype[self.cmdtype]: show_list2, 'link': links, 'num': num, 'leftsides': self.left[self.cmdtype], 'rightside': self.right, 'username': self.username}
            return admintemplate.render(**a)
        
    def delete(self):
        '''
        删除元素
        '''
        list_to_del = request.POST.getall('del')
        if list_to_del:
            for todel in list_to_del:
                delit = self.model[self.cmdtype].get_by_id(ids=int(todel))
                if self.cmdtype == 'category':
                    dairies = BlogModel.all().filter('category = ', delit.category).fetch(1000)
                    if dairies:
                        for dairy in dairies:
                            #删除评论
                            oldcomment = CommentModel.all().filter('dairyid = ', int(dairy.key().id())).fetch(1000)
                            if oldcomment:
                                for com in oldcomment:
                                    com.delete()
                            #删除tag
                            for tag in dairy.tag:
                                oldtag = TagModel.all().filter('tag = ', tag).get()
                                if oldtag:
                                    oldtag.num -= 1
                                    if oldtag.num == 0:
                                        oldtag.delete()
                            dairy.delete()
                if self.cmdtype == 'comment':
                    dairy = self.model['blog'].get_by_id(ids=delit.dairyid)
                    dairy.comments -=1
                    dairy.save()
                if self.cmdtype == 'blog':
                    #删除评论
                    oldcomment = CommentModel.all().filter('dairyid = ', int(todel)).fetch(1000)
                    if oldcomment:
                        for com in oldcomment:
                            com.delete()
                    #删除tag
                    oldcategory = CategoryModel.all().filter('category = ', delit.category).get()
                    oldcategory.num -= 1
                    oldcategory.save()
                    for tag in delit.tag:
                        oldtag = TagModel.all().filter('tag = ', tag).get()
                        if oldtag:
                            oldtag.num -= 1
                            if oldtag.num == 0:
                                oldtag.delete()
            delit.delete()
            self.redirect('success')
        else:
            self.redirect('fail')
            
    def edit(self, key):
        '''
        编辑元素
        '''
        editit = self.model[self.cmdtype].get_by_id(ids=int(key))
        if not editit:
            self.redirect('fail')
        else:
            admintemplate = adminlookup.get_template(self.cmdtype+'_edit.tpl')
            if self.cmdtype == 'blog':
                categories = CategoryModel().all()
                tag = ''
                if editit.tag:
                    for tagstr in editit.tag[:-1]:
                        tag += tagstr + ','
                    tag += editit.tag[-1]
                if not editit.briefview:
                    editit.briefview = ''
                a = {'webpage': self.webpage, 'categories': categories, self.showtype[self.cmdtype]: editit, 'tag': tag, 'leftsides': self.left[self.cmdtype], 'rightside': self.right, 'username': self.username}
            else:
                a = {'webpage': self.webpage, self.showtype[self.cmdtype]: editit, 'leftsides': self.left[self.cmdtype], 'rightside': self.right, 'username': self.username}
            return admintemplate.render(**a)
    
    def accept_edit(self, key):
        '''
        提交编辑
        '''
        if self.cmdtype == 'blog':
            result = {
                'author': self.webpage['owner'],
                'title': datavalid(data=request.forms.get('title'), datatype='title'),
                'content': request.forms.get('content').decode('UTF-8'),
                'url': datavalid(data=request.forms.get('url'), datatype='articleurl'),
                'tag': datavalid(data=request.forms.get('tag'), datatype='tag'),
                'category': datavalid(data=request.forms.get('category'), datatype='author'),
                'new_category': datavalid(data=request.forms.get('new_category'), datatype='author'),
                'brief': request.forms.get('brief').decode('UTF-8'),
                'save': request.forms.get('save'),
                'post': request.forms.get('post'),
                'year': datetime.date.today().year,
                'month': datetime.date.today().month,
                'day': datetime.date.today().day,
                'time': datetime.datetime.now() + datetime.timedelta(hours=self.webpage['timeoffset']),
            }
            
            #如果有新建分类，则使用新建分类，否则，使用默认分类
            if result['new_category']:
                result['article_category'] = result['new_category']
                oldcategory = CategoryModel.all().filter('category = ', result['article_category']).get()
                if not oldcategory:
                    category = CategoryModel()
                    category.category = result['article_category']
                    category.num = 0
                    category.save()
                else:
                    oldcategory.num -= 1
                    oldcategory.save()

            else:
                result['article_category'] = result['category']
            #如果有tag，则分离tag
            if result['tag'] == [' ']:
                result['tags'] = [' ']
            elif result['tag']:
                result['tags'] = []
                result['tags'] = result['tag'].split(',')
            #判断是否发布
            if result['post']:
                result['posted'] = True
            else:
                result['posted'] = False
            #无key即为发布，有key即为修改
            if not key:
                addin = BlogModel()
                addin.readtimes = 0
                addin.comments = 0
                addin.time = result['time']
            else:
                #原先存在的文章需要处理原先tag，否则会导致tag数重复累加
                addin = BlogModel.get_by_id(ids=int(key))
                tag = addin.tag
                category = addin.category
                #如果tag栏中的tag是原先文章的，则将tag区域内的这条tag的计数减一
                for tags in result['tags']:
                    if tags in tag:
                        tagbefore = TagModel.all().filter('tag = ', tags).get()
                        if tagbefore:
                            tagbefore.num -= 1
                            tagbefore.save()
                            if tagbefore.num <= 0:
                                tagbefore.delete()
                           
                                
                #同样分类也需要这样处理
                catebefore = CategoryModel.all().filter('category = ', category).get()
                if catebefore:
                    catebefore.num -= 1
                    catebefore.save()
                #如果原先文章中的tag不在tag栏中，则将tag区域内的这条tag的计数减一          
                for tags in addin.tag:
                    if not tags in result['tags']:
                        tagbefore = TagModel.all().filter('tag = ', tags).get()
                        if tagbefore:
                            tagbefore.num -= 1
                            tagbefore.save()
                            if tagbefore.num <= 0:
                                tagbefore.delete()
            
            if result['content']:
                if result['url']:
                    if result['title']:
                            addin.title = result['title']
                            addin.author = result['author']
                            if result['brief']:
                                addin.briefview = result['brief']
                            else:
                                addin.briefview = ''
                            addin.category = result['article_category']
                            addin.content = result['content']
                            addin.day = result['day']
                            addin.month = result['month']
                            addin.year = result['year']
                            addin.posted = result['posted']
                            addin.url = result['url']
                            if result['tag']:
                                addin.tag = result['tags']
                                #保存tag
                                for new_tag in result['tags']:
                                    oldtag = TagModel.all().filter('tag = ', new_tag).get()
                                    if oldtag:
                                        oldtag.num += 1
                                        oldtag.save()
                                    else:
                                        tag = TagModel()
                                        tag.tag = new_tag
                                        tag.num = 1
                                        tag.save()
                            addin.save()
                            #分类个数加1
                            category = CategoryModel.all().filter('category = ', result['article_category']).get()
                            if category:
                                category.num += 1
                                category.save()
                            self.redirect('success')
            self.redirect('fail')
        else:
            addin = self.model[self.cmdtype].get_by_id(ids=int(key))
            if not addin:
                self.redirect('fail')
            result = {
                'author': datavalid(data=request.forms.get('author'), datatype='author'),
                'email': datavalid(data=request.forms.get('email'), datatype='email'),
                'content': datavalid(data=request.forms.get('content'), datatype='content'),
                'url': datavalid(data=request.forms.get('webpage'), datatype='url'),
            }
            if all(result):
                addin.content = result['content']
                addin.email = result['email']
                addin.author = result['author']
                addin.webpage = result['url']
                addin.save()
                self.redirect('success')
            self.redirect('fail')
    
    def post(self):
        categories = CategoryModel().all()
        admintemplate = adminlookup.get_template(self.cmdtype+'_post.tpl')
        a = {'webpage': self.webpage, 'categories': categories, 'leftsides': self.left[self.cmdtype], 'rightside': self.right, 'username': self.username}
        return admintemplate.render(**a)
    
    def change(self):
        change = request.POST.get('change')
        if change:
            key = request.POST.get('chg')
            return self.accept_change(key)
        else:
            return self.delete()
        

    def accept_change(self, key):
        '''
                        修改分类
        '''
        change = self.model[self.cmdtype].get_by_id(ids=int(key))
        if not change:
            self.redirect('fail')
        else:
            new = datavalid(data=request.POST.get('changevalue'), datatype='author')
            if not new:
                self.redirect('fail')
            else:
                if self.cmdtype=='category':
                    diaries = BlogModel.all().filter("category = ", change.category)
                    if diaries:
                        for diary in diaries:
                            diary.category = new
                            diary.save()
                    change.category = new
                    change.save()
                self.redirect('success')

    def redirect(self, state):
        '''
        链接跳转
        '''
        redirect(redirect('/admincp/'+self.cmdtype+'/'+state))